using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Net.Http;
using Newtonsoft.Json.Linq;

namespace PddWebAuto.SmsHandler
{
    internal class WebPhoneApi : ISMSAPI
    {
        private string _COM_ = "";
        private bool _IsUse_;
        private string _Phone_ = "";
        private string _Url_ = "";
        private string Error = "";
        private readonly Func<string[]> GetListPhone;
        public int IndexItem = -1;

        public WebPhoneApi(Func<string[]> GetList)
        {
            GetListPhone = GetList;
        }

        public async Task<string> WaitSms(int Second, params string[] Args)
        {
            var Sms = "";
            var _time = DateTime.Now;
            _IsUse_ = true;
            do
            {
                await TaskHelper.Delay(5 * 1000);

                if ((DateTime.Now - _time).TotalSeconds >= Second)
                {
                    Error = "获取超时";
                    return null;
                }

                Sms = GetSms(_COM_, _Phone_);
            } while (string.IsNullOrEmpty(Sms));

            return Regex.Match(Sms, "验证码是([0-9]*)")?.Groups[1]?.Value ?? "";
        }

        public async Task<string> GetPhone(int ReNum)
        {
            IndexItem = -1;
            var CP = GetListPhone?.Invoke();
            if (CP != null && CP.Length == 3)
            {
                _COM_ = CP[0];
                _Phone_ = CP[1];
                IndexItem = int.Parse(CP[2]);
                return _Phone_;
            }

            await Task.CompletedTask;
            Error = "无可用号码";
            return null;
        }

        public string GetMsg()
        {
            return Error;
        }

        public bool IsUse()
        {
            return _IsUse_;
        }

        public bool SetUrl(string Url)
        {
            try
            {
                var U = new Uri(Url);
                var Keys = HttpUtility.ParseQueryString(U.Query);
                _Url_ = U.Scheme + "://" + U.Authority + "/listforjson.php?Room=" + Keys.Get("Room");
                return true;
            }
            catch (Exception)
            {
            }

            return false;
        }

        private string GetSms(string COM, string Phone)
        {
            try
            {
                var Html = Send();
                if (!string.IsNullOrEmpty(Html))
                {
                    var Json = JArray.Parse(Html);
                    foreach (var item in Json)
                    {
                        if ((string)item["com"] != COM)
                        {
                            continue;
                        }

                        var updatetime = (DateTime)item["updatetime"];
                        if ((DateTime.Now - updatetime).TotalMinutes < 4)
                        {
                            var msg = (string)item["msg"];
                            if (msg.Contains("拼多多"))
                            {
                                return msg;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Error = ex.Message;
            }

            return null;
        }

        private string Send()
        {
            Error = string.Empty;
            var Item = new HttpItem
            {
                Method = "GET",
                URL = _Url_,
                Timeout = 5 * 1000
            };
            Item.Timeout = 5 * 1000;
            Item.Encoding = Encoding.UTF8;
            var Res = Item.Send();
            if (Res.IsSuccessStatusCode)
            {
                return Res.Html;
            }

            Error = "网络错误";
            return null;
        }
    }
}